package model

import (
	"context"
	"gorm.io/gorm"
	"time"
)

type User struct {
	Id         int64
	Username   string
	Password   string
	CreateTime time.Time
	UpdateTime time.Time
	DeleteTime time.Time
	IsDelete   int64
	Version    int64
	Phone      string
	Avatar     string `gorm:"column:avatar;type:varchar(255);default:''"`
}

type (
	UserModel struct {
		DB *gorm.DB
	}

	UserModelInterface interface {
		Create(ctx context.Context, user *User) (id int64, err error)
		CheckUsernameExist(ctx context.Context, username string) bool
		FindById(ctx context.Context, id int64) (user *User, err error)
	}
)

func (u *UserModel) FindById(ctx context.Context, id int64) (user *User, err error) {
	//TODO implement me
	userModel := &User{}
	err = u.DB.WithContext(ctx).
		Select("id, username, avatar, create_time, update_time").
		Where("id = ?", id).
		First(userModel).Error
	if err != nil {
		return userModel, err
	}

	return userModel, nil
}

func (u *UserModel) CheckUsernameExist(ctx context.Context, username string) bool {
	result := u.DB.WithContext(ctx).
		Select("id").
		Where("username = ?", username).
		First(&User{})
	if result.Error != nil {
		return false
	}

	return true
}

func (u *UserModel) Create(ctx context.Context, user *User) (id int64, err error) {
	result := u.DB.WithContext(ctx).Create(user)
	return result.RowsAffected, result.Error
}

func NewUserModel(DB *gorm.DB) *UserModel {
	return &UserModel{
		DB: DB,
	}
}
